package fetch;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;

public class GetThread extends Thread 
{
	public GetThread(String uid)
	{
		this.uid = uid;
	}
	
	public JSONObject getCurrentJpage()
	{
		return (JSONObject) jpage.get();
	}
	
	public void run() 
	{
		JSONObject jo = getJSONBskkPage(uid);
		
		if(jo!=null)
			jpage.set(jo);
			
	}
	
	public static JSONObject getJSONBskkPage(String uid)
	{
		String sUrl = "";
		
		HttpClient httpclient = new DefaultHttpClient();
		
		JSONArray pagings = new JSONArray();
		
		JSONObject jpage = new JSONObject();
		
		boolean flag = false;
		
		try
		{
			sUrl = "http://bskk.com/forum.php?mod=viewthread&tid=" + uid ;
			
			//System.out.println("current url: " + sUrl);
			
			for(int i = 1 ; i < 200 ; i ++)
			{
				JSONObject paging = new JSONObject();
				// Create an instance of HttpGet.
				HttpGet httpget = new HttpGet(sUrl + "&extra=&page=" + i);
							
				// Create a response handler
				ResponseHandler<String> responsehandler = new BasicResponseHandler();
							
				String responseBody = httpclient.execute(httpget,responsehandler);
				
				
				if(responseBody.indexOf("下一页")<0)
				{
					paging.put("page"+ i, responseBody);
					pagings.add(paging);
					break;
				}
				
				paging.put("page"+ i, responseBody);
				
				pagings.add(paging);
				
				
			}
			
			
		}catch(Exception e)
		{
			System.out.println("<----  " +  "Error page url: " + sUrl   + "  ---->");
			
			e.printStackTrace();
			
		}finally
		{
			httpclient.getConnectionManager().shutdown();
		}
		
		
		jpage.put("surl", sUrl);
		
		jpage.put("body", pagings);
		
		if(!isIncludeKeyWord(pagings,"日日慈"))//过滤其他帖子，只保留日日慈帖子
			return null;
		System.out.println("page.size  : " + pagings.size());
		return jpage;
	}
	
	
	public static boolean isIncludeKeyWord(JSONArray pagings, String keyword)
	{
		boolean flag = false;
		
		if (pagings == null || pagings.size() == 0)
				return false;
		for(int i = 0 ; i < pagings.size() ; i++)
		{
			 int pagenum = i +1;
			 
			 JSONObject paging = (JSONObject) pagings.get(i);
			 
			if(paging.get("page" + pagenum).toString().indexOf(keyword) >= 0)
			{
				flag = true;
				
				break;
			}
		}
		
		return flag;
	}
	
	
	private String uid;
	private ThreadLocal jpage = new ThreadLocal();

	
}
